package com.iteaj.oauth2.client.action;

import com.iteaj.framework.spi.auth.SecurityException;
import com.iteaj.framework.autoconfigure.FrameworkProperties;
import com.iteaj.framework.result.HttpResult;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * create time: 2021/3/27
 *  根据客户端类型自动选择OAuth2授权动作
 * @author iteaj
 * @since 1.0
 */
public abstract class DefaultOAuth2Action implements OAuth2Action {

    private String[] urlPattern;
    private FrameworkProperties config;

    public DefaultOAuth2Action(String[] urlPattern) {
        this.urlPattern = urlPattern;
    }

    @Override
    public String getLoginUrl() {
        return null;
    }

    /**
     * Oauth2回调后登录成功时跳转的地址
     * @return
     */
    public String getSuccessUrl() {
        return null;
    }

    @Override
    public String[] getUrlPattern() {
        return this.urlPattern;
    }

    @Override
    public boolean doAuthorize(String url, HttpServletRequest request, HttpServletResponse response) throws SecurityException {
        if(isAjax(request)) {
            // 写出结果
            writeJson(HttpResult.Success(url,"生成授权url成功"), response);
        } else {

            // 重定向Oauth2授权地址到授权服务器
            try {
                response.sendRedirect(url);
            } catch (IOException e) {
                throw new SecurityException("[Oauth2]重定向失败", e);
            }
        }

        return true;
    }

    @Override
    public boolean loginCall(Exception cause, HttpServletRequest request, HttpServletResponse response) {
        try {
            // 登录成功重定向到成功页面
            if(cause == null) {
                response.sendRedirect(getSuccessUrl());
            } else {
                writeJson(HttpResult.Fail("登录失败"), response);
            }
        } catch (IOException e) {
            throw new SecurityException(e);
        }

        return true;
    }

    public DefaultOAuth2Action setUrlPattern(String[] urlPattern) {
        this.urlPattern = urlPattern;
        return this;
    }

    public FrameworkProperties getConfig() {
        return config;
    }

    @Autowired
    public DefaultOAuth2Action setConfig(FrameworkProperties config) {
        this.config = config;
        return this;
    }
}
